//ES6 导入模块
const db = require("../DBHelper");
const moment = require("moment");
class Cart {
  async add(req, res) {
    let { uid, gid, gname, gprice, gnumber, gurl, gsize } = req.body;
    let sql_select = "select * from cart where cstatus=1 and gid=? and uid=? ;";
    let sql_params = [gid, uid];
    let queryResult = await db.exec(sql_select, sql_params);
    let isAdd = queryResult && queryResult.length >= 1;
    if (isAdd) {
      let sql_update =
        "update cart set cnumber=cnumber+?,cmoney=cnumber*cprice where gid=? and uid=? ;";

      let updateResult = await db.exec(sql_update, [gnumber, gid, uid]);
      let isUpdate = updateResult.affectedRows >= 1;
      res.json({
        msg: isUpdate ? "加入购物车成功" : "加入购物车失败",
      });
    } else {
      let sql_insert =
        "insert into cart (uid,gid,cname,curl,cprice,csize,cnumber,cmoney,createtime) value(?,?,?,?,?,?,?,?,?);";
      let date = moment().format("YYYY-MM-DD HH:mm:ss");
      let prams = [
        uid,
        gid,
        gname,
        gurl,
        gprice,
        gsize,
        gnumber,
        gnumber * gprice,
        date,
      ];
      let insertResult = await db.exec(sql_insert, prams);
      let isInsert = insertResult && insertResult.affectedRows >= 1;
      res.json({
        msg: isInsert ? "加入购物车成功" : "加入购物车失败",
      });
    }
  }

  //查看
  async getcarts(req, res) {
    let sql = "select * from cart where cstatus=1 and uid=? ;";
    let result = await db.exec(sql, [req.params.uid]);
    res.json({ msg: "查询成功", data: result, code: 1 });
  }

  async modifiy(req, res) {
    let sql =
      "update cart set cnumber=? ,cmoney=cnumber*cprice where cid=? and cstatus=1";
    let params = [req.body.cnumber, req.body.cid];
    let result = await db.exec(sql, params);
    let isModifiy = result.affectedRows >= 1;
    res.json({
      msg: isModifiy ? "修改成功" : "修改失败",
      code: isModifiy ? 1 : -1,
    });
  }
  //软删除
  async delete(req, res) {
    let sql = "update cart set cstatus=0 where cid=? and cstatus=1";
    let params = [req.body.cid];
    let result = await db.exec(sql, params);
    let isModifiy = result.affectedRows >= 1;
    res.json({
      msg: isModifiy ? "删除成功" : "删除失败",
      code: isModifiy ? 1 : -1,
    });
  }
}

//nodejs暴露模块
module.exports = new Cart();
